import socket
import threading
import os
from config import HOST, PORT
from model_loader import load_model
from client_handler import handle_client

def start_server():
    """创建和启动TCP服务器"""
    # 确保数据保存目录存在
    os.makedirs('./csvdata', exist_ok=True)
    os.makedirs('./plotdata', exist_ok=True)
    
    # 加载模型
    model, device = load_model()

    # 创建服务器套接字
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    try:
        server.bind((HOST, PORT))
        server.listen(5)
        print(f"服务器在 {HOST}:{PORT} 上监听中...")

        while True:
            client, addr = server.accept()
            client_thread = threading.Thread(target=handle_client, args=(client, addr, model, device))
            client_thread.daemon = True
            client_thread.start()

    except KeyboardInterrupt:
        print("服务器关闭中...")
    except Exception as e:
        print(f"服务器错误: {e}")
    finally:
        server.close()

if __name__ == "__main__":
    start_server()